﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.JsonPatch;

namespace Demo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };
        private static readonly List<UserInfo> _users = new List<UserInfo>
        {
            new UserInfo{ Id=1, Address="地址11", Age=23, Name="张三" },
            new UserInfo{ Id=2, Address="地址22", Age=23, Name="李四" },
            new UserInfo{ Id=3, Address="地址33", Age=23, Name="王五" },
            new UserInfo{ Id=4, Address="地址44", Age=23, Name="赵六" },
            new UserInfo{ Id=5, Address="地址55", Age=23, Name="狗七" },
            new UserInfo{ Id=6, Address="地址66", Age=23, Name="候八" },
        };


        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpPatch]
        [Route("")]
        public List<UserInfo> Patch([FromBody]JsonPatchDocument<UserModel> model)
        {
            var user = _users.Where(x => x.Id == 1).FirstOrDefault();
            model.ApplyTo(user);
            Update(user);

            return _users;
        }

        public void Update(UserInfo m)
        {
            foreach (var item in _users)
            {
                if (item.Id == m.Id)
                {
                    _users.Remove(item);
                    _users.Add(m);
                }
            }
        }
    }





}
